package com.subaiqiao.yunshiyuan.entrance.ysy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.subaiqiao.yunshiyuan.basis.controller.BasisController;
import com.subaiqiao.yunshiyuan.basis.utils.Result;
import com.subaiqiao.yunshiyuan.entrance.ysy.pojo.UserInfo;
import com.subaiqiao.yunshiyuan.entrance.ysy.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 曹朝禹
 * @since 2022-05-13
 */
@RestController
@RequestMapping("/ysy/user-info")
@Api(tags = "用户信息")
public class UserInfoController extends BasisController<UserInfo, UserInfoService> {

    @Override
    public UserInfoService getService() {
        return userInfoService;
    }

    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation("查询所有用户信息")
    @GetMapping("/FindUserPage.do")
    public Result FindPage(
            @RequestParam @ApiParam("页码") Integer pageNum,
            @RequestParam @ApiParam("数量") Integer pageSize,
            @RequestParam(defaultValue = "") @ApiParam("用户名") String username,
            @RequestParam(defaultValue = "") @ApiParam("邮箱") String email,
            @RequestParam(defaultValue = "") @ApiParam("手机号") String phone
            ){
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.like("username",username)
                .like("email", email)
                .like("phone", phone);
        IPage<UserInfo> page = new Page<>(pageNum, pageSize);
        return Result.success(userInfoService.page(page,wrapper));
    }

    @ApiOperation("查询用户详情")
    @GetMapping("/FindUserDetail.do")
    public Result FindUserDetail(@RequestParam @ApiParam("用户编号") Integer userId){
        return Result.success(userInfoService.getById(userId));
    }

    @ApiOperation("添加/修改一个用户")
    @PostMapping("/InsertUser.do")
    public Result InsertUser(UserInfo entity){
        boolean result = false;
        if(entity.getUserId()==null) {
            if(entity.getPhone()!=null && !entity.getPhone().equals("")) {
                QueryWrapper<UserInfo> wrapper_phone = new QueryWrapper<>();
                wrapper_phone.eq("phone", entity.getPhone());
                if(userInfoService.getOne(wrapper_phone)!=null){
                    return Result.error("手机号重复！");
                }
            }
            if(entity.getEmail()!=null && !entity.getEmail().equals("")){
                QueryWrapper<UserInfo> wrapper_email = new QueryWrapper<>();
                wrapper_email.eq("email", entity.getEmail());
                if(userInfoService.getOne(wrapper_email)!=null){
                    return Result.error("邮箱重复！");
                }
            }
            QueryWrapper<UserInfo> wrapper_username = new QueryWrapper<>();
            wrapper_username.eq("username", entity.getUsername());
            if(userInfoService.getOne(wrapper_username)!=null){
                return Result.error("用户名重复！");
            }
            entity.setUserType(1);
            result = userInfoService.save(entity);
        }
        else {
            if(entity.getPhone()!=null && !entity.getPhone().equals("")) {
                QueryWrapper<UserInfo> wrapper_phone = new QueryWrapper<>();
                wrapper_phone.eq("phone", entity.getPhone()).ne("user_id",entity.getUserId());
                if(userInfoService.getOne(wrapper_phone)!=null){
                    return Result.error("手机号重复！");
                }
            }
            if(entity.getEmail()!=null && !entity.getEmail().equals("")){
                QueryWrapper<UserInfo> wrapper_email = new QueryWrapper<>();
                wrapper_email.eq("email", entity.getEmail()).ne("user_id",entity.getUserId());
                if(userInfoService.getOne(wrapper_email)!=null){
                    return Result.error("邮箱重复！");
                }
            }
            QueryWrapper<UserInfo> wrapper_username = new QueryWrapper<>();
            wrapper_username.eq("username", entity.getUsername()).ne("user_id",entity.getUserId());
            if(userInfoService.getOne(wrapper_username)!=null){
                return Result.error("用户名重复！");
            }
            result = userInfoService.updateById(entity);
            if(result){
                return Result.success(userInfoService.getById(entity.getUserId()));
            }
        }
        if(result) return Result.success();
        return Result.error();
    }

    @ApiOperation("封禁一个用户")
    @DeleteMapping("/DeleteUser.do")
    public Result DeleteUser(@RequestParam @ApiParam("用户编号") Integer userId){
        if(userId==1)return Result.error("管理员root不允许被删除！");
        return Result.success(userInfoService.removeById(userId));
    }

    @ApiOperation("登录")
    @PostMapping("/Login.do")
    public Result Login(@RequestParam String username,
                        @RequestParam String password) {
        try {
            return Result.success(getService().Login(username, password));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation("管理员登录")
    @PostMapping("/RootLogin.do")
    public Result RootLogin(@RequestParam String username,
                            @RequestParam String password) {
        try {
            return Result.success(getService().RootLogin(username, password));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation("验证码登录")
    @PostMapping("/ViefLogin.do")
    public Result ViefLogin(@RequestParam String Phone,
                            @RequestParam String ViefCode){
        try {
            return Result.success(getService().ViefLogin(Phone, ViefCode));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }


    @ApiOperation("根据旧密码修改密码")
    @PostMapping("/ChangePasswordByOldPassword.do")
    public Result ChangePasswordByOldPassword(@RequestParam String username,
                                              @RequestParam String oldPassword,
                                              @RequestParam String newPassword) {
        try {
            return Result.success(getService().ChangePasswordByOldPassword(username, oldPassword, newPassword));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation("根据手机验证码修改密码")
    @PostMapping("/ChangePasswordByPhone.do")
    public Result ChangePasswordByPhone(@RequestParam(defaultValue = "") String username,
                                        @RequestParam(defaultValue = "") String phone,
                                        @RequestParam String ViefCode,
                                        @RequestParam String newPassword) {
        try {
            return Result.success(getService().ChangePasswordByPhone(username, phone, ViefCode, newPassword));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * TODO 要换成用Redis缓存的
     * @param request
     * @return
     */
    @ApiOperation("根据Token登录")
    @PostMapping("/LoginByToken.do")
    public Result Tk(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        QueryWrapper<UserInfo> wrapper_user = new QueryWrapper<>();
        wrapper_user.eq("token",token);
        UserInfo user = userInfoService.getOne(wrapper_user);
        if(user==null){
            return Result.error();
        }else{
            return Result.success(user);
        }
    }

    @ApiOperation("查询所有用户数量")
    @GetMapping("/FindUserCount.do")
    public Result FindUserCount(){
        try {
            return Result.success(userInfoService.FindUserCount());
        }catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation("查询已被禁用的用户数量")
    @GetMapping("/FindUserDisabledCount.do")
    public Result FindUserDisabledCount(){
        try {
            return Result.success(userInfoService.FindUserDisabledCount());
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation("查询昨日注册人数")
    @GetMapping("/FindUserYesterdayRegister.do")
    public Result FindUserYesterdayRegister(){
        try {
            return Result.success(userInfoService.FindUserYesterdayRegister());
        }catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

}
